package mymongo

import (
	"mygo/mystruct"
	"time"
	"fmt"
)

/* =================================================================================
   登录缓存操作
*/
// 获取缓存
func Get_Chcae_User(aestring string, key []byte) *mystruct.Muser {
	if aestring == "" {
		return nil
	}
	clientsMu.Lock()
   	defer clientsMu.Unlock()

   	account, err := mystruct.Decrypt(aestring, key) // 通行证秘钥解密获得账号
   	if err != nil {
   		return nil
   	}
    //destr := strings.Split(plaintext, "-")
	obj, ok := MYUSER_CACHE[account]
	if (ok) {
		obj.Time = time.Now()
		return &obj.User
	}
	return nil
}
// 添加缓存
func Add_Chcae_User(account string, result mystruct.Muser, ipstring, UserAgent string, key []byte) string {
    clientsMu.Lock()
    defer clientsMu.Unlock()

    t := time.Now()
    ciphertext, _ := mystruct.Encrypt(account, key) // 账号秘钥加密生成通行证
    usercli := fmt.Sprintf("%s - %s", ipstring, UserAgent)

    obj, ok := MYUSER_CACHE[account]
    if (ok) {
    	// 有其他客户端在登录
    	for _, v := range obj.Gs {
			if v == usercli {
				return ciphertext // 同源客户端返回
			}
		}
		obj.Time = time.Now()
		obj.Gs = append(obj.Gs, usercli) // 添加新客户端
		return ciphertext
	}
    MYUSER_CACHE[account] = &mystruct.Musercode{result, []string{usercli}, t} // 添加新用户
    return ciphertext
}
// 查看所有缓存
func See_Chcae_User() map[string][]string {
    clientsMu.Lock()
    defer clientsMu.Unlock()
    result := make(map[string][]string)
    for key, value := range MYUSER_CACHE {
	     result[key] = value.Gs
	 }
    return result
}
// 验证删除缓存
func Logout_Chcae_User(account, aestring, ipstring, UserAgent string, key []byte) {
    clientsMu.Lock()
    defer clientsMu.Unlock()
	obj, ok := MYUSER_CACHE[account]
    if (ok) {
    	for i, v := range obj.Gs {
			if v == fmt.Sprintf("%s - %s", ipstring, UserAgent) {
				obj.Gs = append(obj.Gs[:i], obj.Gs[i+1:]...)
				break
			}
		}
		if len(obj.Gs) == 0 { // 没有客户端连接则删除用户登录缓存
			delete(MYUSER_CACHE, account)
		}	
	}
}
// 直接删除缓存
func Del_Chcae_User(account string) {
	clientsMu.Lock()
   	defer clientsMu.Unlock()
   	delete(MYUSER_CACHE, account)
}
// 修改缓存
func Set_Chcae_User(account string) {
	clientsMu.Lock()
   	defer clientsMu.Unlock()
   	delete(MYUSER_CACHE, account)
}